//@Author: wulinlin
//@Description:
//@File:  enterprise_v1
//@Version: 1.0.0
//@Date: 2024/04/22 21:46

package enterprise_service

import (
	"context"
	"ebip/internel/domain"
	"ebip/internel/repository/repo"
	"ebip/internel/service"
	"ebip/pkg/logger"
	"fmt"
	"github.com/xuri/excelize/v2"
)

type parserV1 struct {
	f    service.FileService
	lg   logger.Logger
	repo repo.EnterpriseRepo
}

func NewEnterParserV1(f service.FileService, lg logger.Logger, repo repo.EnterpriseRepo) EnterParser {
	return &parserV1{f: f, lg: lg, repo: repo}
}

func (e *parserV1) parser(titleMap map[string]int, row []string) domain.EnterpriseBasicDM {
	company := domain.EnterpriseBasicDM{}
	val, ok := titleMap["企业名称"]
	if ok {
		company.CompanyName = row[val]
	}
	val, ok = titleMap["登记状态"]
	if ok {
		company.RegStatus = row[val]
	}
	val, ok = titleMap["法定代表人"]
	if ok {
		company.LegalBoss = row[val]
	}
	val, ok = titleMap["注册资本"]
	if ok {
		company.RegCapital = row[val]
	}
	//val, ok = titleMap["成立日期"]
	//if ok {
	//	company.EstablishmentDate = row[val]
	//}
	val, ok = titleMap["统一社会信用代码"]
	if ok {
		company.SocialCode = row[val]
	}
	val, ok = titleMap["企业注册地址"]
	if ok {
		company.CompanyRegAddr = row[val]
	}
	val, ok = titleMap["电话"]
	if ok {
		company.Phone = row[val]
	}
	val, ok = titleMap["更多电话"]
	//if ok {
	//	company.MorePhone = row[val]
	//}
	val, ok = titleMap["邮箱"]
	if ok {
		company.Email = row[val]
	}
	val, ok = titleMap["更多邮箱"]
	//if ok {
	//	company.MoreEmail = row[val]
	//}
	return company
}

func (p *parserV1) ParserEnterpriseExcel(ctx context.Context, filePath string) error {
	// 1. 校验参数 2.校验文件是否存在 3. 校验文件种子(是否已经解析过) 4.解析文件 5.返回解析结果
	_, err := p.f.GetFileInfo(ctx, filePath)
	if err != nil {
		return err
	}
	// 开始解析Excel文件
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		return err
	}
	defer f.Close() // 关闭文件读写

	sheetName := f.GetSheetName(0)
	// 获取第一个工作表的行数和列数
	rows, err := f.GetRows(sheetName)
	if err != nil {
		p.lg.Error("获取工作表的行信息失败", logger.Error(err), logger.String("文件路径：", filePath))
		return err
	}
	titleMap := make(map[string]int, 20)
	for i, row := range rows {
		if i == 0 {
			continue
		}
		if i == 1 {
			// 第一次进来遍历第一行，就可以获取map表结构
			for ik, cell := range row {
				titleMap[cell] = ik
			}
			continue
		}
		company := p.parser(titleMap, row)
		fmt.Println(company)
		err = p.repo.AddEnterpriseBaseInfo(ctx, 1, "excel-load", company)
		if err != nil {
			return err
		}
	}
	return nil
}
